package com.jhs.demo.dragimgs;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by wangqi on 2018/8/1.
 */
public class DragImageView extends FrameLayout implements View.OnLongClickListener {

    private List<Integer> mList = new ArrayList<>();

    // 长按之后的间距
    private int padding = 10;

    private DragState state = DragState.NORMAL;
    //悬浮在最外层的view
    private ImageView tempView;
    //按下的坐标
    private float downX;
    private float downY;

    //正在执行动画
    private boolean isAnimatling;

    // 长按的position
    private int mDragPosition;

    enum DragState {
        NORMAL, DRAGING
    }

    public DragImageView(@NonNull Context context) {
        this(context, null);
    }

    public DragImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DragImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void addView() {
        //添加imageview
        try {
            removeAllViews();
            for (int i = 0; i < mList.size(); i++) {
                ImageView imageView = new ImageView(getContext());
                imageView.setTag(i);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setImageResource(mList.get(i));
                // 设置事件监听
                imageView.setOnLongClickListener(this);
//                imageView.setOnTouchListener(this);

                LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                if (i == 0) {
                    params.width = getWidth() / 2;
                    params.height = getHeight();
                } else {
                    params.width = getWidth() / 4;
                    params.height = getHeight() / 2;
                    if (i == 1) {
                        params.leftMargin = getWidth() / 2;
                    } else if (i == 2) {
                        params.leftMargin = getWidth() * 3 / 4;
                    } else if (i == 3) {
                        params.leftMargin = getWidth() / 2;
                        params.topMargin = getHeight() / 2;
                    } else if (i == 4) {
                        params.leftMargin = getWidth() * 3 / 4;
                        params.topMargin = getHeight() / 2;
                    } else {
                        break;
                    }
                }
                addView(imageView, params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onLongClick(View view) {
        state = DragState.DRAGING;

        mDragPosition = (int) view.getTag();
        //最上层增加一个view
        tempView = new ImageView(getContext());
        tempView.setTag(-1);
        tempView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        tempView.setImageResource(mList.get(mDragPosition));

        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        LayoutParams viewParams = (LayoutParams) view.getLayoutParams();
        params.width = viewParams.width - padding * 2;
        params.height = viewParams.height - padding * 2;
        params.leftMargin = viewParams.leftMargin + padding;
        params.topMargin = viewParams.topMargin + padding;

        addView(tempView, params);
        //隐藏长按的view
        view.setVisibility(GONE);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = motionEvent.getX();
                downY = motionEvent.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (state == DragState.DRAGING) {
                    View v = findViewWithTag(-1);
                    float moveX = motionEvent.getX();
                    float moveY = motionEvent.getY();
                    v.setTranslationX(getX() + moveX - downX);
                    v.setTranslationY(getY() + moveY - downY);
                    // 滑动过程中 做位置变换
                    int position = getPositionByXY(moveX, moveY);
                    if (position != mDragPosition && !isAnimatling) {
                        viewPositionChange(position, mDragPosition);
                        mDragPosition = position;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                state = DragState.NORMAL;
                if (tempView != null) {
                    removeView(tempView);
                }
                refreshView();
                break;
        }
        return super.onInterceptTouchEvent(motionEvent);
    }

    /**
     * 执行交换位置动画
     *
     * @param position
     * @param mDragPosition
     */
    private void viewPositionChange(final int position, final int mDragPosition) {
        final ImageView view = findViewWithTag(position);
        final ImageView dragView = findViewWithTag(mDragPosition);

        final LayoutParams params = (LayoutParams) view.getLayoutParams();
        final LayoutParams dragParams = (LayoutParams) dragView.getLayoutParams();

        AnimationSet animationSet = new AnimationSet(true);

        //平移动画
        TranslateAnimation translateAnimation = new TranslateAnimation(0.0f,
                dragParams.leftMargin - params.leftMargin,
                0.0f,
                dragParams.topMargin - params.topMargin);
        translateAnimation.setDuration(200);
        translateAnimation.setFillAfter(false);
        animationSet.addAnimation(translateAnimation);
        //缩放动画
        if (position == 0 || mDragPosition == 0) {
            float scale = position == 0 ? -2 : 2;

            ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, scale, 1.0f, scale,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setDuration(200);
            scaleAnimation.setFillAfter(false);
            animationSet.addAnimation(scaleAnimation);
        }

        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isAnimatling = false;
                view.setVisibility(GONE);
                dragView.setVisibility(VISIBLE);
                dragView.setImageResource(mList.get(position));
                //修改tempView的大小
                if (mDragPosition == 0) {
                    //缩小
                    LayoutParams layoutParams = (LayoutParams) tempView.getLayoutParams();
                    layoutParams.width /= 2;
                    layoutParams.height /= 2;
                    layoutParams.leftMargin += tempView.getWidth() / 4;
                    layoutParams.topMargin += tempView.getHeight() / 4;
                } else if (position == 0) {
                    // 放大
                    LayoutParams layoutParams = (LayoutParams) tempView.getLayoutParams();
                    layoutParams.width *= 2;
                    layoutParams.height *= 2;
                    layoutParams.leftMargin -= tempView.getWidth() / 2;
                    layoutParams.topMargin -= tempView.getHeight() / 2;
                }
                Collections.swap(mList, position, mDragPosition);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        view.startAnimation(animationSet);
        isAnimatling = true;
    }

    /**
     * 通过坐标获取 位置position
     *
     * @param x
     * @param y
     * @return
     */
    private int getPositionByXY(float x, float y) {
        int position;
        if (x <= getWidth() / 2) {
            position = 0;
        } else if (x > getWidth() / 2 && x <= getWidth() * 3 / 4) {
            if (y <= getHeight() / 2) {
                position = 1;
            } else {
                position = 3;
            }
        } else {
            if (y <= getHeight() / 2) {
                position = 2;
            } else {
                position = 4;
            }
        }
        return position;
    }

    public void setData(List<Integer> list) {
        if (list != null && list.size() != 0) {
            mList.clear();
            mList.addAll(list);
            refreshView();
        }
    }

    public void refreshView() {
        post(new Runnable() {
            @Override
            public void run() {
                addView();
            }
        });
    }

}
